#include "DatetimeUtil.h"

#include <math.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <time.h>

void CDatetimeUtil::GetCurrentTime(int *year, int *month, int *day, int *hour, int *minu, int *sec)
{
#ifdef XNLINUX
    time_t timep;
    struct tm *p;
    time(&timep);
    p=localtime(&timep);
    *year = p->tm_year+1900;
    *month =p->tm_mon+1;
    *day = p->tm_mday;
    *hour =p->tm_hour;
    *minu = p->tm_min;
    *sec = p->tm_sec;
#endif
}

void CDatetimeUtil::GetSystemTime(char time_buf[50])
{
    int year,month,day, hour, minu,sec;
    GetCurrentTime(&year,&month,&day,&hour,&minu,&sec);
    sprintf(time_buf, "time:%04d-%02d-%02d %02d:%02d:%02d", year, month, day, hour, minu, sec);
}

//修改linux的系统时间和硬件时间
void CDatetimeUtil::SetLocalTime(const QDateTime& dt)
{
    SetSystemTime(dt.date().year()
                  , dt.date().month()
                  , dt.date().day()
                  , dt.time().hour()
                  , dt.time().minute()
                  , dt.time().second()
                  );
}

void CDatetimeUtil::SetSystemTime(quint16 usYear, quint16 usMonth, quint16 usDay, quint16 usHour, quint16 usMin, quint16 usSec)
{
    // set system datetime
    struct tm nowtime;
    time_t t;

    nowtime.tm_sec =  usSec;         /* Seconds.[0-60](1 leap second)*/
    nowtime.tm_min =  usMin;         /* Minutes.[0-59] */
    nowtime.tm_hour = usHour;       /* Hours. [0-23] */
    nowtime.tm_mday = usDay;        /* Day.[1-31]  */
    nowtime.tm_mon =  usMonth - 1;   /* Month.[0-11] */  //月份，范围从 0 到 11
    nowtime.tm_year = usYear - 1900;/* Year- 1900. */   //自 1900 起的年数
    nowtime.tm_isdst = -1;          /* DST.[-1/0/1]*/

    t = mktime(&nowtime);
    ctime(&t);

    // set to COMS
    quint16 iRetVal = 0;
    if (0 == fork()) //子进程号固定为0
    {
        if (execlp("/sbin/hwclock", "hwclock", "-w", "-u", (char*)0) < 0)
        {
            iRetVal = -4;
        }
    }
    wait(NULL); //等待子进程结束
}
